package com.wang.mandkey.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

import javax.swing.JTextArea;

import com.wang.mandkey.tool.ScriptRunnerThread;
import com.wang.mandkey.utils.ProjectEnvironment;

/**
 * 接受手机端请求的线程，这个线程理论上一直运行在电脑上
 * 
 * @author wangzy
 * 
 */
public class ServerThread implements Runnable {

	private ServerSocket serverSocketServer;
	private Socket socketClient;
    private ScriptRunnerThread scriptRunnerThread;
    private boolean booleanAlive=true;
    private Thread thread=null;
    private int intPort=ProjectEnvironment.INT_DEFAULT_PORT_COMMAND;
    private JTextArea jta;
	public ServerThread(InetAddress address,Integer intPort,JTextArea jta) {
		try {
			serverSocketServer = new ServerSocket();
			SocketAddress socketAddress=new InetSocketAddress(address, intPort); 
			serverSocketServer.bind(socketAddress);
			
			this.intPort=intPort;
			this.jta=jta;
		} catch (IOException e) {
			e.printStackTrace();
			killSelf();
		}

	}

	@Override
	public void run() {

		System.out.println("server thread is tart...");
        this.jta.append("服务开启...\n");
       
		while (booleanAlive) {
			try {
				
				if(null==serverSocketServer || serverSocketServer.isClosed()==false){
					if(null!=serverSocketServer){
					serverSocketServer.close();
					}
					serverSocketServer = new ServerSocket(intPort);
					
				}

				if(serverSocketServer.isClosed()==false){
					socketClient = serverSocketServer.accept();
					socketClient.setReceiveBufferSize(4);
//					socketClient.setKeepAlive(true);
//					System.out.println("request:"+socketClient.getInetAddress().getHostAddress());
					this.jta.append("请求来自:"+socketClient.getInetAddress().getHostAddress()+"\n");
					if(scriptRunnerThread!=null){
						scriptRunnerThread.killSlef();
					}
					scriptRunnerThread=new ScriptRunnerThread(socketClient ,new INetCallBack() {
						@Override
						public void onNetInterupt() {
							jta.append("命令端口关闭!\n");
						}
					},jta);
					scriptRunnerThread.startMe();
				}else{
					break;
				}
			
				
			} catch (IOException e) {
				e.printStackTrace();
				killSelf();
				break;
			}

		}

	}

	public void StartMe(){
		thread=new Thread(this);
		thread.start();
	}
	public void killSelf(){
		booleanAlive=false;
		closeServerSocket();
		if(scriptRunnerThread!=null){
			scriptRunnerThread.killSlef();
		}
		
	}
	public void closeServerSocket() {
		
		if (null != serverSocketServer&& serverSocketServer.isClosed() == false) {
			try {
				serverSocketServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		killSelf();

	}

}
